﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Configuration;
using System.Xml;

namespace Inspector
{
    /// <summary>   
    /// 插入到终结点的Behavior   
    /// </summary>   
    public class MyEndPointBehavior : Attribute, IServiceBehavior, IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            // 不需要   
            return;
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            // 植入“偷听器”客户端   
            clientRuntime.MessageInspectors.Add(new Inspector());
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            // 植入“偷听器” 服务器端   
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new Inspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            // 不需要   
            return;
        }



        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            WsdlExporter wsdlExporter = new WsdlExporter();
            wsdlExporter.ExportEndpoints(serviceDescription.Endpoints,
                new XmlQualifiedName(serviceDescription.Name, serviceDescription.Namespace));

            foreach (ChannelDispatcher cDispatcher in serviceHostBase.ChannelDispatchers)
                foreach (EndpointDispatcher endpointDispatcher in cDispatcher.Endpoints)
                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
                        new Inspector());

        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }
    }
}
